import time

from zz import zz_code, zz_dingtalk, zz_return, zz_log, zz_str
import requests
import sys

log = zz_log.of()


def run(job_id=None):
    token = zz_code.env("MZ_TOKEN")
    token_arr = zz_str.split2(token)
    log.info(token_arr)
    if token_arr is None:
        log.error('未配置MZ_TOKEN')
        return

    log_msg = '**工作日报** \n\n'
    for item in token_arr:
        handle = Handle(item[0], None, job_id)

        log_msg_one = handle.run_one()
        print(log_msg_one)
        log.info(log_msg_one)
        log_msg += log_msg_one + "\n\n"

    zz_dingtalk.send_markdown(log_msg, "工作日报")


# 民政工作日报
class Handle:
    def __init__(self, token, date=None, job_id=None):
        self.token = token
        self.date = date
        if self.date is None:
            self.date = zz_code.date_tostring(format='%Y-%m-%d')

        self.job_id = job_id
        if zz_str.is_null_or_empty(job_id):
            self.job_id = 'scgb0023100'  # 顶度中台

    def run_one(self):
        if zz_str.is_null_or_empty(self.token):
            return "缺少参数"
        log_msg = ''
        do_add = self.api_work_add()
        if not do_add:
            log_msg += f"{self.date}日志-已填写"
            return log_msg
        # 填写日志
        sumbit = self.api_work()
        if sumbit:
            log_msg += f"{self.date}日志-填写成功"
        else:
            log_msg += f"{self.date}日志-填写失败"

        return log_msg

    def get_headers(self):
        headers = {
            "Cookie": f"AccountCookieV1902={self.token}"
        }
        user_agent = zz_code.env("USER_AGENT")
        if zz_str.has_any_text(user_agent):
            headers['User-Agent'] = user_agent

        return headers

    # 签到
    def api_work(self):
        api_url = f"http://bi.jmeii.com/App/AppRepoAdd/_t16i3023565_"
        headers = self.get_headers()

        post_data = {
            "成本归属": self.job_id,  # 顶度
            "成本项": 'scrf1337198',
            "填报数量": '7.5',
            "类型": '新增',
            "发生日期": self.date,
        }

        log.info(api_url)
        log.info(headers)
        log.info(post_data)
        res = requests.post(api_url, data=post_data, headers=headers)
        r = zz_return.of(123456, "提交失败")
        if res.ok:
            r = zz_return.of(0, "成功")

        return r

    # 是否填写日志
    def api_work_add(self) -> bool:
        api_url = f"http://bi.jmeii.com/App/AppTableList2/t16i3023565_{self.date}"
        headers = self.get_headers()
        log.info(api_url)
        log.info(headers)
        # log.debug(post_data)
        res = requests.get(api_url, headers=headers)
        html_b = res.content
        html = zz_str.bytes_to_str(html_b)
        return zz_str.contains(html, '还未填报任何项目')

    def to_return(self, content) -> zz_return.Return:
        log.info(content)
        try:
            r = zz_return.parse(content)
            errcode = r.get_data('code')
            errmsg = r.get_data('message')
            r.set_errmsg(errmsg)
            r.set_errcode(errcode)
        except Exception as ex:
            log.error(ex)
            r = zz_return.of(123456, ex)
        log.info(f"return: {r.to_json()}")

        return r


if __name__ == '__main__':
    args = sys.argv[1:]
    job_id = None
    if len(args) > 0:
        job_id = args[0]
    # job_id = 't5jb2913821'
    run(job_id)
